package com.csr.csrcheck.controller;

import com.csr.csrcheck.pojo.News;
import com.csr.csrcheck.service.ex.CompanyException;
import com.csr.csrcheck.service.impl.NewsServiceImpl;
import com.csr.csrcheck.util.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

@RestController
@RequestMapping({"news"})
public class NewsController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(com.csr.csrcheck.controller.NewsController.class);

    @Resource
    private NewsServiceImpl newsService;

    @GetMapping({"newlist"})
    public JsonResult<List<News>> getAllNews() {
        List<News> list = this.newsService.getAllNews();
        return new JsonResult(Integer.valueOf(0), "json", list);
    }

    @RequestMapping({"newApi"})
    public String api() throws IOException {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            String connUrl = "https://www.apiopen.top/journalismApi";
            URL url = new URL(connUrl);
            conn = (HttpURLConnection)url.openConnection();
            conn.setUseCaches(false);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String strRead = null;
            while ((strRead = reader.readLine()) != null)
                sb.append(strRead);
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null)
                reader.close();
            if (conn != null)
                conn.disconnect();
        }
        return rs;
    }

    @GetMapping({"byidnews/{id}"})
    public JsonResult<News> byidnews(@PathVariable("id") Integer id) {
        News news = this.newsService.getnewsbyid(id);
        if (news == null)
            throw new CompanyException("");
                    log.info("byidnews-------------------------->id:" + id);
        return new JsonResult(Integer.valueOf(0), "json", news);
    }

    @RequestMapping(path = {"deletenews/{id}"})
    public JsonResult<Void> deletenews(@PathVariable("id") int id) {
        this.newsService.deleteNews(id);
        return new JsonResult(Integer.valueOf(0), "json");
    }
}
